#include "stdafx.h"
#include "MutliUI.h"
#include "UIMain.h"
#include <GameLogic/BoardLogicServer.h>
#include <GameLogic/BoardLogicClient.h>
#include "UIController.h"
#include "CatanStratryTest.h"

namespace catan
{
	MutliUI::MutliUI(void)
	{
		
	}
	
	MutliUI::~MutliUI(void)
	{
	}

	void MutliUI::Run()
	{
		SimpleLog::Init(_T("catan.log"));
		SimpleLog::Instance().SetPriorityLevel(PriorityLevel::Debug);
		typedef std::list<UIMain*> UIMains;
		UIMains uis;

		BoardFactory f;
		// 	Handle<Board> b = f.Create4Board();
		// 	std::ostringstream oss;
		// 	boost::archive::binary_oarchive os(oss);
		// 	os & b;
		BoardLogicServer server;
		//server.GameStart();
		const int Num = 4;
		std::vector<BoardLogic*> boardLogics;
		std::vector<Helper*> helpers;
		std::vector<IHelperBase*> helperbases;
		for (int i = 0; i < Num; ++i)
		{
			Helper* helper = new Helper();
			helpers.push_back(helper);
			UIMain* u = new UIMain();
			u->SetHelper(helper);
			u->Init();

			BoardLogicClient* client = new BoardLogicClient();
			boardLogics.push_back(client);
			helper->SetBoardLogic(client);
			client->SetColor(PlayerColor::Enum(i));
			helper->SetHostColor(PlayerColor::Enum(i));
			BoardLogicClient::ServerSender* ss = new BoardLogicClient::ServerSender(client);
			boardLogics.push_back(ss);
			client->SetServer(ss);
			client->RegisterEvents();
			u->SetLogic(client);
			UIController* uiController = new UIController();
			helper->SetUiController(uiController);
			helperbases.push_back(uiController);
			uiController->SetColor(PlayerColor::Enum(i));
			client->SetIO(uiController);
			uiController->SetHelper(helper);
			uiController->SetServer(client);
			uiController->Init();
			BoardLogicServer::ClientSender* c = new BoardLogicServer::ClientSender(ss);
			boardLogics.push_back(c);
			ss->SetSender(c);
			c->SetServer(&server);
			c->SetColor(PlayerColor::Enum(i));
			server.AddClient(c);

			uis.push_back(u);
			
		}
		server.RegisterEvents();
		server.GameStart();
		while (!uis.empty())
		{
			bool exit = false;
			for (UIMains::iterator it(uis.begin());
				it != uis.end(); ++it)
			{
				if (!(*it)->Tick())
				{
					exit = true;
				}

			}
			CatanStratryTest::Instance().DoAll();

			Sleep(40);

			if (exit)
			{
				for (UIMains::iterator it(uis.begin());
					it != uis.end(); ++it)
				{
					(*it)->Close();
				}
				break;
			}
		
		}
		
		SafeDeleteAll(uis);
		SafeDeleteAll(helpers);
		SafeDeleteAll(helperbases);
		SafeDeleteAll(boardLogics);
		SimpleLog::UnInit();
	}
} 